package com.example.sunflowers.ui

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ShareCompat
import androidx.core.widget.NestedScrollView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import cn.trans88.taxiappkotlin.ext.logd
import cn.trans88.taxiappkotlin.ext.loge
import com.example.sunflowers.R
import com.example.sunflowers.data.db.Plant
import com.example.sunflowers.databinding.FragmentPlantDetailBinding
import com.example.sunflowers.viewmodels.PlantDetailViewModel
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.concurrent.thread

@AndroidEntryPoint
class PlantDetailFragment : Fragment() {

    private val plantDetailViewModel:PlantDetailViewModel by viewModels()
    lateinit var binding: FragmentPlantDetailBinding
    lateinit var currentPlant: Plant

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        "plantDetailFragment onCreate".logd()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        "plantDetailFragment onCreateView".logd()
//        thread {
//            plantDetailViewModel.getPlantById()
//        }
        plantDetailViewModel.refreshPlant()
        binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
            inflater,
            R.layout.fragment_plant_detail,
            container,
            false
        )
        binding.apply {
            viewModel = plantDetailViewModel
            "plant:${plantDetailViewModel.plant.value?.toString()}".loge()
            lifecycleOwner = viewLifecycleOwner
            callback = Callback { plant ->
                plant?.let {
                    hideAppBarFab(fab)
                    plantDetailViewModel.addPlantToGarden()
                    Snackbar.make(root,R.string.added_plant_to_garden,Snackbar.LENGTH_LONG).show()
                }
            }

            galleryNav.setOnClickListener { navigateToGallery() }

            var isToolbarShown = false
            plantDetailScrollview.setOnScrollChangeListener(
                NestedScrollView.OnScrollChangeListener{ _, _,scrollY,_,_ ->
                    val shouldShowToolbar = scrollY > toolbar.height
                    if (isToolbarShown != shouldShowToolbar){
                        isToolbarShown = shouldShowToolbar
                        appbar.isActivated = shouldShowToolbar
                        toolbarLayout.isTitleEnabled = shouldShowToolbar
                    }
                }
            )

            toolbar.setNavigationOnClickListener {
                it.findNavController().navigateUp()
            }

            toolbar.setOnMenuItemClickListener { item ->
                when(item.itemId){
                    R.id.action_share -> {
                        createShareIntent()
                        true
                    }
                    else -> false
                }
            }
        }
        plantDetailViewModel.plant.observe(viewLifecycleOwner){
            "plantId observe ${it.plantId}".loge()


        }

        setHasOptionsMenu(true)
        // Inflate the layout for this fragment
        return binding.root
    }

    @Suppress("DEPRECATION")
    private fun createShareIntent() {
        val shareText = plantDetailViewModel.plant.value.let { plant ->
            if (plant == null) {
                ""
            } else {
                getString(R.string.share_text_plant, plant.name)
            }
        }
        val shareIntent = ShareCompat.IntentBuilder.from(requireActivity())
            .setText(shareText)
            .setType("text/plain")
            .createChooserIntent()
            .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
        startActivity(shareIntent)
    }

    private fun hideAppBarFab(fab:FloatingActionButton){
        val params = fab.layoutParams as CoordinatorLayout.LayoutParams
        val behavior = params.behavior as FloatingActionButton.Behavior
        behavior.isAutoHideEnabled = false
        fab.hide()
    }

    private fun navigateToGallery(){
        plantDetailViewModel.plant.value?.let { plant ->
            val direction = PlantDetailFragmentDirections.actionPlantDetailFragmentToGalleryFragment(plant.name)
            findNavController().navigate(direction)
        }
    }

    fun interface Callback{
        fun add(plant: Plant?)
    }

    override fun onResume() {
        super.onResume()
        "plantDetailFragment onResume".logd()
    }

//    fun getPlant2(){
//        "getPlant2".loge()
//        plantDetailViewModel.plant.observe(this.viewLifecycleOwner){
//            "it.name ---> ${it.name}".loge()
//        }
//    }

}